package com.acmetelecom.core;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import com.acmetelecom.call.Call;
import com.acmetelecom.call.CallEnd;
import com.acmetelecom.call.CallEvent;
import com.acmetelecom.call.CallLogger;
import com.acmetelecom.call.CallStart;
import com.acmetelecom.customer.Customer;
import com.acmetelecom.customer.CustomerDatabase;
import com.acmetelecom.customer.Tariff;
import com.acmetelecom.customer.TariffLibrary;

public class BillingSystem {

    private CallLogger callLogger;
    
	private BillGenerator billGenerator;

	private final TariffLibrary centralTariffDatabase;

	private final CustomerDatabase customerDb;

    public void createCustomerBills() {
        List<Customer> customers = customerDb.getCustomers();
        for (Customer customer : customers) {
            createBillFor(customer);
        }
        callLogger.clear();
    }

    private void createBillFor(Customer customer) {
        List<Call> calls = this.callLogger.getCompletedCalls(customer);
        BigDecimal totalBill = new BigDecimal(0);
        List<LineItem> items = new ArrayList<LineItem>();

        for (Call call : calls) {

            Tariff tariff = centralTariffDatabase.tarriffFor(customer);

            BigDecimal cost;

            cost = new BigDecimal( DaytimePeakPeriod.getOffPeakSeconds( call.startTime(), call.endTime() ) ).multiply( tariff.offPeakRate() ).add(
            		new BigDecimal( DaytimePeakPeriod.getOnPeakSeconds( call.startTime(), call.endTime() ) ).multiply( tariff.peakRate() ) );
            
            cost = cost.setScale(0, RoundingMode.HALF_UP);
            BigDecimal callCost = cost;
            totalBill = totalBill.add(callCost);
            items.add(new LineItem(call, callCost));
        }

        billGenerator.send(customer, items);
    }
    
    public BillingSystem(CallLogger callLogger, BillGenerator billGenerator, TariffLibrary centralTariffDb, CustomerDatabase customerDb2) {
    	this.callLogger = callLogger;
    	this.billGenerator = billGenerator;
    	this.centralTariffDatabase = centralTariffDb;
    	this.customerDb = customerDb2;
    }

	public void log(CallStart event) {
		callLogger.log(event);
	}
	
	public void log(CallEnd event) {
		callLogger.log(event);
	}
}
